<template>
  <div class="newAddPrice" ref="main">
    <BasicModal
      @register="registerNewAddModal"
      :title="t('table.race_price.form_newAdd')"
      v-bind="$attrs"
      @ok="okSubmit"
      :width="560"
      :okText="t('table.promotion.promotion_confirm_add')"
      cancelText=""
      :getContainer="() => $refs.main"
    >
      <BasicForm @register="registerFromNewAdd" />
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { message } from 'ant-design-vue';
  import { defineEmits, ref } from 'vue';
  import { getAdBidsChannelDetail, postAdBidsInsert } from '/@/api/promotion';

  const { t } = useI18n();

  interface Item {
    label: string;
    value: number;
  }
  const emit = defineEmits(['activeSuccess', 'register']);
  const options = ref<Item[]>();
  const isSubmit = ref(false);
  const channel_id = ref('');

  const schemas: FormSchema[] = [
    {
      field: 'gid',
      component: 'Select',
      label: t('table.advertise.table_grouping_name') + ':',
      defaultValue: '',
      required: true,
      componentProps: () => {
        return {
          options: options.value,
          size: 'large',
          allowClear: false,
          getPopupContainer: () => document.body,
        };
      },
    },
    {
      field: 'username',
      component: 'Input',
      label: t('table.race_price.form_agent_account') + ':',
      defaultValue: '',
      componentProps: {
        size: 'large',
        placeholder: t('table.promotion.promotion_p_tips'),
      },
      rules: [
        {
          required: true,
          validator: async (_, value) => {
            if (!value) {
              return Promise.reject(t('table.promotion.promotion_p'));
            }
            const { data, status } = await getAdBidsChannelDetail({ agent_account: value });
            if (status) {
              const { channel_name, id } = data;
              channel_id.value = id;
              if (!isSubmit.value) {
                await setFieldsValue({ channel_name: channel_name });
              }
              if (!channel_name) {
                return Promise.reject(t('table.promotion.promotion_tips'));
              }
              return Promise.resolve(); // 校验通过
            } else {
              return Promise.reject(t('table.promotion.promotion_tips'));
            }
          },

          trigger: 'blur',
        },
      ],
    },
    {
      field: 'channel_name',
      component: 'Input',
      label: t('table.promotion.promotion_agency_account') + ':',
      defaultValue: '',
      componentProps: {
        size: 'large',
        disabled: true,
        allowClear: false,
      },
    },
    {
      field: 'prepay',
      component: 'Input',
      label: t('table.race_price.table_prepayment_u') + ':',
      defaultValue: '',
      componentProps: {
        size: 'large',
      },
      rules: [
        {
          required: true,
          validator: (_, value) => {
            if (!value) {
              return Promise.reject(t('table.promotion.promotion_p_enter_prepayment_u'));
            }
            const regex = /^((0\.+\d+)|[1-9]\d*)(\.\d+)?$/;
            if (!regex.test(value)) {
              return Promise.reject(t('table.promotion.promotion_prepayment_u_tips'));
            }
            return Promise.resolve();
          },
          trigger: 'blur',
        },
      ],
    },
    {
      field: 'fee',
      component: 'Input',
      label: t('table.race_price.table_service_fee') + ':',
      defaultValue: '',
      componentProps: {
        size: 'large',
      },
      rules: [
        {
          required: true,
          validator: (_, value) => {
            if (!value) {
              return Promise.reject(t('table.promotion.promotion_p_enter_service_fee'));
            }
            const regex = /^(0|[1-9]\d*)(\.\d+)?$/;
            if (!regex.test(value)) {
              return Promise.reject(t('table.system.system_incorrect_format'));
            }
            return Promise.resolve();
          },
          trigger: 'blur',
        },
      ],
    },
  ];
  const [registerNewAddModal, { closeModal }] = useModalInner(async (selectList) => {
    options.value = selectList
      .filter((item, index) => index != 0)
      .map((item) => {
        return {
          label: item.name,
          value: item.id,
        };
      });
    if (options.value) {
      setFieldsValue({ gid: options.value[0].value.toString() });
    }
  });

  const [registerFromNewAdd, { validate, setFieldsValue, resetFields }] = useForm({
    schemas,
    showActionButtonGroup: false,
    labelWidth: 100,
    baseColProps: { span: 24 },
  });

  async function okSubmit() {
    isSubmit.value = true;
    let values;

    try {
      values = await validate();
    } catch (error) {
      console.error('Validation failed:', error);
    } finally {
      isSubmit.value = false; // 在这里确保 isSubmit 一定会被设置为 false
    }

    if (values) {
      values.channel_id = channel_id.value;
      console.log(values, 'values');
      const { status, data } = await postAdBidsInsert(values);
      if (status) {
        closeModal();
        resetFields();
        message.success(t('layout.setting.operatingTitle'));
        emit('activeSuccess');
      } else {
        message.error(data);
      }
    }
  }
</script>
<style lang="scss" scoped>
  .newAddPrice {
    ::v-deep(.ant-form) {
      border-bottom: 1px solid #dce3f1;
    }

    ::v-deep(.ant-form-item-label > label) {
      display: flex;
    }

    ::v-deep(.ant-form-item-no-colon) {
      justify-content: end;
      width: 86px;
      height: auto !important;
      margin-right: 5px;
      line-height: 40px !important;
    }

    ::v-deep(.ant-modal .ant-modal-body > .scrollbar) {
      padding: 30px 35px 0;
    }

    ::v-deep(.ant-form-item-label) {
      width: 100px !important;
    }

    ::v-deep(.ant-modal-footer) {
      padding: 20px 16px;
    }

    ::v-deep(.ant-checkbox-group-item) {
      width: 72px;
      margin-right: 12px;
      margin-bottom: 5px;
      white-space: nowrap;
    }

    ::v-deep(.ant-checkbox-group) {
      width: 290px;
    }
  }
</style>
